package com.yangxk.kadmin.common.util;

import javax.servlet.http.HttpServletRequest;

public class IpUtil {
    private IpUtil(){}

    public final static String ERROR_IP = "127.0.0.1";

    /**
     * 获取客户端IP
     * create by yangxk on 2018/9/13 11:16
     */
    public static String getIp(HttpServletRequest request) {
        // 优先取X-Real-IP
        String ip = request.getHeader("X-Real-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if ("0:0:0:0:0:0:0:1".equals(ip)) {
                ip = ERROR_IP;
            }
        }

        if ("unknown".equalsIgnoreCase(ip)) {
            ip = ERROR_IP;
            return ip;
        }

        int pos = ip.indexOf(',');
        if (pos >= 0) {
            ip = ip.substring(0, pos);
        }

        return ip;
    }
}
